package com.fjrz.bbxwj.main.mine

import android.Manifest
import android.app.Activity
import android.content.Intent
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.app.RZApplication
import com.fjrz.bbxwj.entity.UserMe
import com.fjrz.bbxwj.entity.UserRequest
import com.fjrz.bbxwj.main.access.AccessActivity
import com.fjrz.bbxwj.main.video.CameraActivity
import com.fjrz.bbxwj.mode.vm.UserViewModel
import com.fjrz.bbxwj.popup.EditUserPopup
import com.fjrz.bbxwj.popup.ProgressPopup
import com.module.lemlin.view.LoadingDialog
import com.module.lemlin.base.loadCircleImage
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.code
import com.module.lemlin.rxhttp.msg
import com.tbruyelle.rxpermissions3.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import kotlinx.android.synthetic.main.activity_info_editing.*

class EditInfoActivity : ViewModeActivity<UserViewModel>() {

    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, EditInfoActivity::class.java)
            activity.startActivity(intent)
        }
    }

    private val mProgressPopup: ProgressPopup by lazy {
        ProgressPopup(context = this, onConfirm = {

        }, onCancel = {
            mProgressPopup.dismiss()
            viewModel.dispose.clear()
        })
    }

    private val mEditUserPopup: EditUserPopup by lazy {
        EditUserPopup(context = this) { content, editType ->
            if (editType == 0) {
                mUserRequest.nickname = content
            } else if (editType == 1) {
                mUserRequest.introduction = content
            }
            viewModel.userProfile(mUserRequest)
        }
    }

    private val mUserRequest = UserRequest()

    override val layoutResId: Int
        get() = R.layout.activity_info_editing

    override fun viewModel(): UserViewModel {
        return createViewModel()
    }

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, view = flUserInfoBar)
    }

    override fun initView() {
        ivUserInfoBack.setOnClickListener { this.finish() }

        RZApplication.userInfoMe()?.let {
            fillData(it)
        }

        ivUserMeAvatar.setOnClickListener {

            val rxPermissions = RxPermissions(this)
            rxPermissions.request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ).subscribe {
                if (!it) {
                    toast(message = "请到设置中开启相关权限")
                } else {
                    Matisse.from((this))
                        .choose(MimeType.ofImage())
                        .countable((true))
                        .maxSelectable(1)
                        .imageEngine(GlideEngine())
                        .theme(R.style.Matisse_Zhihu1)
                        .forResult((100))
                }
            }
        }

        flUserMeName.setOnClickListener {
            mEditUserPopup.setTitle("编辑昵称")
                .setText(tvUserMeName.text.toString())
                .setHint("请输入昵称")
                .setType(0)
                .showPopupWindow()
        }

        flUserMeDesc.setOnClickListener {
            mEditUserPopup.setTitle("个人简介")
                .setText(tvUserMeDesc.text.toString())
                .setHint("请输入个人简介")
                .setType(1)
                .showPopupWindow()
        }

        flUserMeIsAuthenticate.setOnClickListener {
            RZApplication.userInfoMe()?.let {
                if (it.certification?.status != 1 && it.certification?.status != 2) {
                    UserAuthActivity.open(activity = this)
                }
            }
        }

    }

    override fun initData() {
        viewModel.userMe()
    }

    override fun initViewMode() {
        viewModel.userMeLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val userMe: UserMe = response.httpData?.data
                ?: return@Observer
            fillData(userMe)
        })

        viewModel.uploadLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.START) {
                if (!mProgressPopup.isShowing)
                    mProgressPopup.showPopupWindow()
                mProgressPopup.resetProgress()
            } else if (response.status == Status.FAILURE) {
                mProgressPopup.dismiss()
                toast(response.throwable?.code, response.throwable?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            mProgressPopup.dismiss()
            response.httpData?.data?.let {
                mUserRequest.avatar = it.url
                viewModel.userProfile(mUserRequest)
            }
        })

        viewModel.userProfileLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (responseStatus2LiveData(response.status, response.throwable) != Status.SUCCESS)
                return@Observer
            mEditUserPopup.dismiss()
            viewModel.userMe()
            toast(message = response.httpData?.msg)
        })

        viewModel.progressLiveData.observe(this as LifecycleOwner, Observer { progress ->
            mProgressPopup.setProgress(progress)
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK) {
            val pathList: MutableList<String> = Matisse.obtainPathResult(data).toMutableList()
            if (pathList.size == 0)
                return
            ivUserMeAvatar.loadCircleImage(pathList[0])
            viewModel.commonUpload(pathList[0])
        }
    }

    private fun fillData(userMe: UserMe) {
        ivUserMeAvatar.loadCircleImage(userMe.avatar)
        tvUserMeName.text = userMe.nickname
        tvUserMePhone.text = userMe.mobile
        if (userMe.introduction.isNullOrEmpty())
            tvUserMeDesc.hint = "个人简介"
        else tvUserMeDesc.text = userMe.introduction

        tvUserMeOrganizeName.text = userMe.merchant_name

        tvUserMeIsAuthenticate.text =
            if (userMe.is_certified_merchant == 1) "已认证" else "未认证"
        tvUserMeOrganizeAuth.text = when (userMe.certification?.status) {
            2 -> {
                "已认证"
            }
            1 -> {
                "审核中"
            }
            else -> {
                "未认证"
            }
        }
    }

    private fun responseStatus2LiveData(status: Status, throwable: Throwable?): Status {
        if (status == Status.START) LoadingDialog.show(
            context = this, resId = R.layout.dialog_load_style_1
        ) else if (status == Status.FAILURE) {
            LoadingDialog.dismiss()
            toast(throwable?.code, throwable?.msg)
        } else {
            LoadingDialog.dismiss()
        }
        return status
    }
}